//
//  LTFTopicView.m
//  NeteaseNews
//
//  Created by liutaifeng on 16/4/13.
//  Copyright © 2016年 liutaifeng. All rights reserved.
//


#import "LTFTopicView.h"
#import "LTFNetWorkingTool.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "LTFTopicModel.h"
#import "LTFTopicCell.h"
#import "IsNight.h"
#import "MJRefresh.h"
#import "LTFTopicBaseHandel.h"
#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height
@interface LTFTopicView ()
<
UITableViewDataSource,
UITableViewDelegate
>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *tableViewArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) NSString *docPath;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) BOOL isCollect;
@end


@implementation LTFTopicView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
        [self createSetUp];
    }
    return self;
}
- (void)createSetUp {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(upData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(moreData)];
}
- (void)upData {
    self.page = 0;
    [self createData];
}
- (void)moreData {
    [self createData];
}

- (void)create {
    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES) lastObject];
    self.docPath = [sandBox stringByAppendingPathComponent:@"topic.plist"];
    NSDictionary * dic = [NSKeyedUnarchiver unarchiveObjectWithFile:_docPath];
    if (dic == nil) {
        [self createData];
    }
    else {
        NSDictionary *data = dic[@"data"];
        NSArray *expertList = data[@"expertList"];
        self.tableViewArray = [LTFTopicModel BaseModelByArray:expertList];
    }
}

- (void)createView {
    self.tableViewArray = [NSMutableArray array];
    self.page = 0;
    [self create];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self addSubview:self.tableView];
    _tableView.tag = 1000;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 300;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableViewArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    LTFTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[LTFTopicCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    LTFTopicModel *model = self.tableViewArray[indexPath.row];
    cell.headImageView.layer.cornerRadius = 25;
    [cell.headImageView setImageWithURL:[NSURL URLWithString:model.headpicurl] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
//    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:model.headpicurl] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    cell.nameAndJobLabel.text = [NSString stringWithFormat:@"%@ / %@", model.name, model.title];
    cell.nameAndJobLabel.font = [UIFont systemFontOfSize:13];
    [cell.picImageView setImageWithURL:[NSURL URLWithString:model.picurl] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
//    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.picurl] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    cell.sortAttentionAndQuestionLabel.font = [UIFont systemFontOfSize:13];
    
    
    cell.contentLabel.text = model.alias;
    NSString *str = [NSString stringWithFormat:@"%@ | %.1f万关注 | %d提问", model.classification, ([model.concernCount intValue] / 10000.0), [model.questionCount intValue]];
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 2)];
    cell.sortAttentionAndQuestionLabel.attributedText = attributedString;
    [cell.attentionButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionButton.tag = 333 + indexPath.row;

    return cell;
    
}
- (void)click:(UIButton *)button {
    self.isCollect = NO;
    LTFTopicModel *model = self.tableViewArray[(button.tag - 333)];
    NSMutableArray *mArray =  [[LTFTopicBaseHandel shareDataBaseTool] select];
    for (NSInteger i = 0; i < mArray.count; i++) {
        if ([mArray[i] isEqualToString:model.expertId]) {
            self.isCollect = YES;
            break;
        }
        else {
            self.isCollect = NO;
        }
    }
    if (self.isCollect == NO) {
        [[LTFTopicBaseHandel shareDataBaseTool] insertModel:model.expertId];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"不可重复收藏" message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
        alertView.alertViewStyle = UIAlertViewStyleDefault;
        [alertView show];
    }
   
}
//点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFTopicModel *model = self.tableViewArray[indexPath.row];
    [self.delegate sendTopicExpertId:model.expertId];
}



#pragma mark 对地址进行解析
- (void)createData {
    //初始化数组
    
    NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/newstopic/list/expert/%ld-10.html", self.page];
    //调用解析方法
    [LTFNetWorkingTool toolWithUrl:str block:^(id result) {
        NSDictionary *dic = result;
        [NSKeyedArchiver archiveRootObject:dic toFile:self.docPath];
        NSDictionary *data = dic[@"data"];
        NSArray *expertList = data[@"expertList"];
        NSArray *array = [LTFTopicModel BaseModelByArray:expertList];
        if (self.page == 0) {
            self.tableViewArray = [NSMutableArray arrayWithArray:array];
        }
        else {
            [self.tableViewArray addObjectsFromArray:array];
        }
        self.page += 10;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    }];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
